<template>
  <div class="table-renderer" :class="mode">
    <!-- 设计模式 -->
    <div v-if="mode === 'design'" class="design-mode">
      <div class="table-preview">
        <div class="table-header-preview">
          <span class="table-title">表格预览</span>
          <span class="table-size">{{ tableData.headers.length }}列 × {{ tableData.data.length + 1 }}行</span>
        </div>
        
        <div class="table-content-preview">
          <el-table
            :data="tableData.data.slice(0, 3)"
            border
            size="mini"
            style="width: 100%"
            :show-header="tableData.showHeader"
            empty-text="暂无数据"
          >
            <el-table-column
              v-for="(header, index) in tableData.headers"
              :key="index"
              :prop="`col${index}`"
              :label="header"
              min-width="80"
            >
              <template #default="scope">
                <span class="cell-preview">{{ scope.row[`col${index}`] }}</span>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="tableData.data.length > 3" class="more-rows">
            <i class="el-icon-more"></i>
            <span>还有 {{ tableData.data.length - 3 }} 行数据</span>
          </div>
        </div>
      </div>
      
      <div class="table-actions">
        <el-button 
          size="mini" 
          @click="editTable"
          icon="el-icon-edit"
        >
          编辑表格
        </el-button>
      </div>
    </div>

    <!-- 预览和生成模式 -->
    <div v-else class="preview-mode">
      <el-table
        :data="processedData"
        border
        size="small"
        style="width: 100%"
        :show-header="tableData.showHeader"
        :class="{ 'no-border': !tableData.border }"
        empty-text="暂无数据"
      >
        <el-table-column
          v-for="(header, index) in processedHeaders"
          :key="index"
          :prop="`col${index}`"
          :label="header"
          :min-width="getColumnWidth(index)"
          align="center"
        >
          <template #default="scope">
            <div class="table-cell" :style="getCellStyle(scope.row, index)">
              {{ scope.row[`col${index}`] }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 表格编辑对话框 -->
    <el-dialog
      title="编辑表格"
      :visible.sync="editDialog.visible"
      width="80%"
      top="5vh"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <table-editor
        v-if="editDialog.visible"
        :table-data="tableData"
        @save="handleTableSave"
        @cancel="editDialog.visible = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import TableEditor from './TableEditor.vue'

export default {
  name: 'TableRenderer',
  components: {
    TableEditor
  },
  props: {
    component: {
      type: Object,
      required: true,
      default: () => ({
        content: {
          headers: ['列1', '列2', '列3'],
          data: [],
          showHeader: true,
          border: true
        }
      })
    },
    config: {
      type: Object,
      default: () => ({})
    },
    mode: {
      type: String,
      default: 'design'
    },
    testData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      editDialog: {
        visible: false
      }
    }
  },
  computed: {
    tableData() {
      return this.component.content || {
        headers: ['参数', '数值', '单位'],
        data: [],
        showHeader: true,
        border: true
      }
    },
    
    processedHeaders() {
      return this.tableData.headers || []
    },
    
    processedData() {
      const data = this.tableData.data || []
      
      // 处理数据中的变量替换
      return data.map(row => {
        const processedRow = { ...row }
        
        Object.keys(processedRow).forEach(key => {
          if (typeof processedRow[key] === 'string') {
            processedRow[key] = this.replaceVariables(processedRow[key])
          }
        })
        
        return processedRow
      })
    }
  },
  methods: {
    /**
     * 编辑表格
     */
    editTable() {
      this.editDialog.visible = true
    },
    
    /**
     * 处理表格保存
     */
    handleTableSave(updatedTableData) {
      this.$emit('update', {
        content: updatedTableData
      })
      this.editDialog.visible = false
    },
    
    /**
     * 获取列宽
     */
    getColumnWidth(index) {
      const baseWidth = 100
      const header = this.processedHeaders[index]
      
      if (!header) return baseWidth
      
      // 根据表头文本长度调整列宽
      const length = header.length
      if (length <= 4) return 80
      if (length <= 6) return 100
      if (length <= 8) return 120
      return 150
    },
    
    /**
     * 获取单元格样式
     */
    getCellStyle(row, columnIndex) {
      const styles = {
        padding: '8px 4px',
        textAlign: 'center'
      }
      
      // 第一列左对齐，其他列居中对齐
      if (columnIndex === 0) {
        styles.textAlign = 'left'
      }
      
      return styles
    },
    
    /**
     * 替换变量
     */
    replaceVariables(text) {
      if (!text || typeof text !== 'string') return text
      
      return text.replace(/\{\{(\w+)\}\}/g, (match, variable) => {
        const value = this.findVariableValue(variable)
        return value !== undefined ? value : match
      })
    },
    
    /**
     * 查找变量值
     */
    findVariableValue(variable) {
      if (!this.testData) return undefined
      
      // 在基本信息中查找
      if (this.testData.basicInfo && this.testData.basicInfo[variable] !== undefined) {
        return this.testData.basicInfo[variable]
      }
      
      // 在参数数据中查找
      let foundValue = undefined
      this.traverseTestData((data, paramCode) => {
        if (paramCode === variable && data.value !== undefined) {
          foundValue = data.value
        }
      })
      
      return foundValue
    },
    
    /**
     * 遍历测试数据
     */
    traverseTestData(callback) {
      if (!this.testData.groups) return
      
      this.testData.groups.forEach(group => {
        if (group.params) {
          Object.keys(group.params).forEach(paramCode => {
            callback(group.params[paramCode], paramCode)
          })
        }
        
        if (group.childGroups) {
          group.childGroups.forEach(childGroup => {
            if (childGroup.params) {
              Object.keys(childGroup.params).forEach(paramCode => {
                callback(childGroup.params[paramCode], paramCode)
              })
            }
          })
        }
        
        if (group.rows) {
          group.rows.forEach(row => {
            Object.keys(row).forEach(paramCode => {
              callback(row[paramCode], paramCode)
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.table-renderer {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.design-mode {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.table-preview {
  flex: 1;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  padding: 8px;
  background: #f8f9fa;
}

.table-header-preview {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e6e8eb;
}

.table-title {
  font-weight: 600;
  color: #303133;
}

.table-size {
  font-size: 12px;
  color: #909399;
}

.table-content-preview {
  max-height: 200px;
  overflow: hidden;
}

.cell-preview {
  font-size: 12px;
  color: #606266;
}

.more-rows {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px;
  color: #909399;
  font-size: 12px;
  background: #f5f7fa;
  border-radius: 2px;
  margin-top: 8px;
}

.table-actions {
  display: flex;
  justify-content: center;
}

.preview-mode {
  width: 100%;
  height: 100%;
}

.table-cell {
  word-break: break-all;
  line-height: 1.4;
}

/* 无边框表格 */
.no-border :deep(.el-table) {
  border: none;
}

.no-border :deep(.el-table__header-wrapper th) {
  border: none;
}

.no-border :deep(.el-table__body-wrapper td) {
  border: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .table-preview {
    padding: 4px;
  }
  
  .table-header-preview {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style>